import { Component, inject, ViewContainerRef } from '@angular/core';
import { SunshineNgZorroAntdModule } from '../ng-zorro-module';
import { RouterOutlet } from '@angular/router';
import { SunshineEmp, Order } from './emp.entity';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SunshineEmpDetailComponent } from './sunshine-emp-detail/sunshine-emp-detail.component';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { baseUrl } from '../../environments/environment.pro';
import { SunshineEmpConstant } from './Constant';
import { SexPipe } from '../pipes/sex-pipe.pipe';
import { NzMessageService } from 'ng-zorro-antd/message';
import { map, Observable } from 'rxjs';
import { NzTableQueryParams } from 'ng-zorro-antd/table';

@Component({
  selector: 'app-sunshine-order',
  standalone: true,
  templateUrl: './sunshine-emp.component.html',
  styleUrls: ['sunshine-emp.component.css'],
  imports: [SunshineNgZorroAntdModule, RouterOutlet, SunshineEmpDetailComponent, SexPipe]
})
export class SunshineEmpComponent {

  emps: SunshineEmp[] = [];
  loading: boolean = true;
  pageSize: number = 10;
  pageIndex: number = 1;
  total: number = 0;
  qryParam: SunshineEmp = new SunshineEmp();
  private http: HttpClient = inject(HttpClient);
  private messageService: NzMessageService = inject(NzMessageService);

  constructor(private modalService: NzModalService, private viewContainerRef: ViewContainerRef,
  ) {

  }
  addModal() {
    console.log('add init 1')
    let sunshineEmp = new SunshineEmp();
    sunshineEmp.isEditable = true;
    const modal = this.modalService.create<SunshineEmpDetailComponent, SunshineEmp>({
      nzTitle: '新增',
      nzContent: SunshineEmpDetailComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzData: sunshineEmp,

      nzFooter: [
        {
          label: '取消',
          type: 'primary',
          onClick: (data: SunshineEmpDetailComponent) => {
            modal.destroy()
            this.ngOnInit();
          }
        }, {
          label: '确定',
          type: 'primary',
          onClick: (data: SunshineEmpDetailComponent) => {
            const p = data.saveEmp((res: any) => {

              modal.destroy();
              this.messageService.create('success', '新增成功');
              this.ngOnInit()
            });
            console.log(p)
            p.then(val => {
              console.log(val)
            }).then((val) => {
              console.log(val)
            },
              () => {
                console.log(333333)
                modal.destroy();
                this.messageService.create('error', '新增失败');
                this.ngOnInit()
              });
            console.log(p)
          }
        },
      ],
    })
  }

  search(): void {
    // this.emps = this.emps.filter((item: SunshineEmp) => item.empName?.indexOf(this.qryParam.orderNo) !== -1);
    this.ngOnInit();
  }

  // 弹框
  createDetailModal(id: number): void {
    console.log("id = " + id)
    this.http.get(SunshineEmpConstant.path.detial + id).subscribe((res: any) => {
      res.extend.emp.isEditable = false;
      const modal = this.modalService.create<SunshineEmpDetailComponent, SunshineEmp>({
        nzTitle: '员工信息',
        nzContent: SunshineEmpDetailComponent,
        nzViewContainerRef: this.viewContainerRef,
        nzData: res.extend.emp,
        nzFooter: [
          {
            label: '关闭',
            type: 'primary',
            onClick: (data: SunshineEmpDetailComponent) => {
              modal.destroy();
              console.log(data.emp)
            }
          },
        ],

      });
    });


  }

  createUpdateComponentModal(id: number): void {
    this.http.request('GET', SunshineEmpConstant.path.detial + '/' + id, { responseType: 'json' }).subscribe((res: any) => {
      res.extend.emp.isEditable = true
      const modal = this.modalService.create<SunshineEmpDetailComponent, SunshineEmp>({
        nzTitle: '员工信息',
        nzContent: SunshineEmpDetailComponent,
        nzViewContainerRef: this.viewContainerRef,
        nzData: res.extend.emp,
        nzFooter: [
          {
            label: '保存',
            type: 'primary',
            onClick: (data: SunshineEmpDetailComponent) => {
              data.updateEmp(() => {
                console.log("createUpdateComponentModal" + 1111)
                modal.destroy();
                this.messageService.create('success', '更新成功');
                this.ngOnInit()
              }).then(res => {
                console.log("createUpdateComponentModal" + 2222)
                alert(res)
                console.log(res)
              });


            }
          },
        ],
      });
    })


  }

  delete(id: number | undefined) {
    console.log('delete id = ' + id);
    this.modalService.confirm({
      nzTitle: '删除订单',
      nzContent: '<b style="color: red;">确定</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: () => {
        // this.emps = this.emps.filter(item => item.empId != id);
        console.log(this.emps.length)
        this.ngOnInit();
      },
      nzCancelText: '取消',
      nzOnCancel: () => console.log('Cancel')
    });
  }

  ngOnInit(): void {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    this.http.post(SunshineEmpConstant.path.list, JSON.stringify(this.qryParam), httpOptions).subscribe((res: any) => {
      console.log(res)
      let data = res.extend.pageInfo;
      console.log("data = " + data);
      this.emps = data.list,
        this.total = data.total;
    });

  }

  loadDataFromServer(
    pageIndex: number,
    pageSize: number,
    // sortField: string | null,
    // sortOrder: string | null,
    // filter: Array<{ key: string; value: string[] }>
    queryParam: SunshineEmp
  ): void {
    this.loading = true;
    queryParam.pageSize = pageSize;
    queryParam.currentPageNo = pageIndex;
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json'
      })
    };
    this.http.post(SunshineEmpConstant.path.list, JSON.stringify(this.qryParam), httpOptions).subscribe((res: any) => {
      console.log(res);
      this.emps = res.extend.pageInfo.list

    });
    // this.randomUserService.getUsers(pageIndex, pageSize).subscribe(data => {
    //   this.loading = false;
    //   this.total = 200; // mock the total data here
    //   this.listOfRandomUser = data.results;
    // });
  }

  onQueryParamsChange(params: NzTableQueryParams): void {
    // console.log(params);
    const { pageSize, pageIndex, sort, filter } = params;
    // const currentSort = sort.find(item => item.value !== null);
    // const sortField = (currentSort && currentSort.key) || null;
    // const sortOrder = (currentSort && currentSort.value) || null;
    // this.loadDataFromServer(pageIndex, pageSize, sortField, sortOrder, filter);
    this.loadDataFromServer(pageIndex, pageSize, this.qryParam);
  }


}

